<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <meta http-equiv="X-UA-Compatible" content="ie=edge"/>
  <meta http-equiv="Access-Control-Allow-Origin" content="*" />
  <title>表情包管理</title>
  <link rel="stylesheet" href="http://tv.speechb.com/lib/bootstrap3/css/bootstrap.min.css">
    <link href="http://tv.speechb.com/lib/select2/css/select2.min.css" rel="stylesheet"/>
  <style>

    body,html{
      margin: 0 auto;
    }
    .up-header {
      width:600px;
      text-align: center;
    }
    .up-content {
      min-height: 200px;
      border: 1px solid #CCCCCC;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      background-color: #FAFAFA;
      color: #999;
      font-size: 20px;
      text-align: center;
    }
    .up-area {
      border: 2px dashed #ccc;
      margin: 10px 20px 20px 20px;
      width: 96%;
      min-height: 200px;
      line-height: 100px;
      background-color: #fff;
    }
    .list-group {
      width: 200px;
      min-height: 100px;
      padding: 10px;
    }
    img {
      max-width: 100%;
    }
    .btn {

    }
    .close {
      margin-left: 550px;
      margin-top: -20px;
    }
	img{
		width:100%;
		height:auto;
	}

  </style>
</head>
<body>


    <!-- 头部显示 -->
    <div class="container upload ">
      <div class="up-header center-block">
        <h2 >表情包发布</h2>
		
		
      </div>
	  
	  <!-- 进度条 -->
	  <div class="progress progress-striped active">
	      <div id="prog" class="progress-bar progress-bar-success" role="progressbar"
	           aria-valuenow="60" aria-valuemin="0" aria-valuemax="100"
	           style="width: 0%;">
	          <span class="sr-only">0% 完成</span>
	      </div>
	  </div>
	  <form id="tf">
        <!-- 点击按钮上传文件 -->
        <div class="up-content btnFile">
          <div class="btn">
            <button type="button" class="btn btn-success" id="btn"> 图片选择</button>
            <input type="file" style="display:none;" id="fileInput" name="files" multiple>
          </div>
          <div class="up-area">
            <div class="row list-btn" style="margin-bottom: 6px;margin-left: 1px;margin-right: 1px;">
              
            </div>
          </div>
        </div>
      </form>

        <div class="form-group form-group-sm row" style="width: 600px;margin-top: 16px">
            <label class="col-sm-2 control-label" for="image_name" style="margin-top: 6px;">表情包名称</label>
            <div class="col-sm-10">
                <input class="form-control" type="text" id="image_name" placeholder="请输入表情包名称">
            </div>
        </div>

        <div class="form-group form-group-sm row" style="width: 600px;margin-top: 16px">
            <label class="col-sm-2 control-label"  style="margin-top: 6px;">&nbsp;&nbsp;类型选择</label>
            <div class="col-sm-10">
                <select id="type_select" name="parentid" class="form-control">
                    <option selected="selected" value="0">--请选择--</option>
                </select>
            </div>
        </div>

        <button type="button"  class="btn btn-primary center-block" id="submitBtn" style="margin-top: 20px"> 发布表情包</button>
    </div>
    <script src="http://tv.speechb.com/lib/superui/content/ui/global/jQuery/jquery.min.js"></script>

    <script src="http://tv.speechb.com/lib/bootstrap3/js/bootstrap.min.js"></script>
    <script src="http://tv.speechb.com/lib/select2/js/select2.full.min.js"></script>
    <script type="text/javascript" charset="utf-8" src="http://tv.speechb.com/lib/toaster/jquery.toaster.js"></script>
   <script type="text/javascript">
    // 文件是否改变标识符
	var uploadFileChangeFlag = false;
	// 存放本次需要上传的图片
    var allImageUploadedUrl = new Array;
	// 本次图片成功后url，用于判断是非全部上传成功
    var currentImageUploadedUrl;
    // 图片上传一个占比，用来显示进度条
    var imageUploadPer = 0;
    // 当前图片上传的占比
    var currentUploadPer = 0;
    var phoneSign;
    var resourceSign;
     //点击本地上传文件
     $('#btn').click( () => {
       $('#fileInput').click();
     })
     $('#fileInput').change( (event) => {
       var files = event.target.files;
       appendFile(files, '.list-btn');
	   console.log($('#fileInput')[0].files);
       uploadFileChangeFlag = true;
     })

      function appendFile (files, listName) {
         currentImageUploadedUrl = new Array(files.length);
          imageUploadPer =  Math.floor(100*1/files.length);
          currentUploadPer = 0;
          $("#prog").css("width",currentUploadPer + "%").text(currentUploadPer + "%");
        for(var i=0;i<files.length;i++) {
            uploadImage(i,files[i],listName);
        }
      }
      $(function(){

          function getSign() {
              $.ajax({
                  type : "GET",
                  url : "/admin/resource_sign",
                  success : function(result) {
                      if(result.code==1) {
                          phoneSign = result.data.sign;
                          resourceSign = result.data.jwt;
                          $.toaster({ priority : "success", title : "通知", message : "获取签证成功!" });
                      } else {
                          $.toaster({ priority : "danger", title : "通知", message : "获取签证失败!" });
                      }
                  },
                  error : function(e){
                      $.toaster({ priority : "danger", title : "通知", message : "获取签证失败!" });
                  }
              });
          }
          getSign();
		  $("#submitBtn").click(function(){
              publishImageBattle();
		  });



          function initSelect2(id,url) {
              $(id).select2({
                  language: "zh-CN",// 指定语言为中午，国际化才能起效
                  inputMessage: "请选择",
                  pagination:{
                      more:true
                  },
                  ajax: {
                      url: url,
                      dataType: 'json',
                      delay:250, // 延迟显示
                      data: function (params) {
                          var query = {
                              search: params.term,
                              page: params.page || 1,
                              rows: 10 //每页显示多少行
                          }

                          // Query parameters will be ?search=[term]&page=[page]
                          return query;
                      },
                      // 分页
                      processResults: function (data, params) {
                          params.page = data.next_page-1;
                          return {
                              results: data.data,// 后台返回数据
                              pagination: {
                                  more: (params.page)*10<data.total// 总数
                              }
                          };
                      },
                      cache: false
                  },
                  escapeMarkup: function (markup) {
                      return markup;
                  },
                  minimumInputLength: 0,// 0长度及搜索所以
                  templateResult: function(repo){// 显示的结果集格式，需要自己写CSS
                      // 正在检索
                      if(repo.loading) return repo.text;
                      var markup = repo.text;
                      var markup = "";
                      markup +="<div class ='select2-result-repository_statistics'>"
                          +"<div class='select2-result-repository_forks'><i class = 'fa fa-bolt'></i> &nbsp;"+repo.text+"</div>"
                          +"</div>";
                      return markup;
                  },
                  templateSelection: function(repo) {
                      // 选中某一列后文本框
                      return "<div>" +repo.text || repo.id + "</div>";
                  },
                  placeholder: '请选择'
              });

          }
          initSelect2("#type_select","/admin/imagebattle/type_select");

          function publishImageBattle () {
              var name = $("#image_name").val();
              var publishType = $("#type_select").val();
              $.ajax({
                  //请求方式
                  type : "POST",
                  //请求地址
                  url : "/admin/imagebattle/publish",
                  //数据，json字符串
                  data : {
                      "type":publishType,
                      "name":name,
                      "image_url_list":JSON.stringify(allImageUploadedUrl)
                  },
                  //请求成功
                  success : function(result) {
                      if(result.code==1) {
                          $(".list-btn").empty();
                          //localStorage.setItem("username",username);
                          //localStorage.setItem("password",password);
                          allImageUploadedUrl = new Array();
                          $.toaster({ priority : "success", title : "通知", message : "发布表情包成功" });
                      } else {
                          $.toaster({ priority : "danger", title : "通知", message : "发布表情包失败" })
                      }
                      console.log(result);
                  },
                  error : function(e){
                      $.toaster({ priority : "danger", title : "通知", message : "发布表情包失败" })
                  }
              });
          }
      });

    /*文件上传,单个文件上传*/
    function uploadImage(index,file,listName) {
        /*if(!uploadFileChangeFlag) {
            $.toaster({ priority : "warning", title : "通知", message : "文件没有变更!" });
            return;
        }*/
        var form = new FormData();
        if(phoneSign==null || resourceSign==null) {
            $.toaster({ priority : "warning", title : "通知", message : "签证有误，正在重新获取!" });
            getSign();
            return;
        }
        form.append("files",file);
        form.append("phone_sign",phoneSign);
        form.append("resource_sign",resourceSign);
        form.append("username","admin");
        $.ajax({
            url:'http://www.tv.speechb.com/magnetw/upload',
            //url:'http://localhost:8080/bt/upload',
            type:'POST',
            cache:false,
            contentType:"multipart/form-data",
            data:form,
            processData:false,
            contentType:false,
            xhr:function(){
                myXhr = $.ajaxSettings.xhr();
                /*if(myXhr.upload){
                    myXhr.upload.addEventListener('progress',function(e){
                        var loaded = e.total;//已经上传大小情况
                        var total = e.total;//附件总大小
                        var per = Math.floor(100*loaded/total);
                        $("#prog").css("width",per + "%").text(per + "%");
                    },false);// for handling the progress of the upload
                }*/
                return myXhr;
            },
            success:function(data){
                if(data.code ==1 ){
                    uploadFileChangeFlag = false;
                    let url = "http://www.tv.speechb.com/"+data.data.img_url_list[0];
                    let liStr = `
                      <div class="col-lg-2 col-md-2 col-sm-3 col-xs-6" style="margin-top:6px">
                        <img src="${url}" alt="文件" style="height:200px;width:150px" class="img-responsive img-thumbnail"/>
                      </div>
                  `;
                   $(listName).append(liStr);
                    currentImageUploadedUrl[index]=data.data.img_url_list[0];
                    allImageUploadedUrl.push(data.data.img_url_list[0]);
                    currentUploadPer += imageUploadPer;
                   $("#prog").css("width",currentUploadPer + "%").text(currentUploadPer + "%");
                   checkCurrentIsUploadFinish();
                } else {
                    $.toaster({ priority : "danger", title : "通知", message : "图片上传失败" });
                }
            },
            error:function(){
                $.toaster({ priority : "danger", title : "通知", message : "图片上传失败" });
            }
        });
    }
    // 坚持本地上传是否结束
    function checkCurrentIsUploadFinish() {
        for (var i=0;i<currentImageUploadedUrl.length;i++) {
            // 存在一个url为空即上传没成功
            if(currentImageUploadedUrl[i]==null) {
                return false;
            }
        }
        console.log(allImageUploadedUrl);
        $.toaster({ priority : "success", title : "通知", message : "本次图片上传全部成功" });
        $("#prog").css("width",100 + "%").text(100 + "%");
        return true;
    }
   </script>

</body>
</html>
